<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>getSnapshotBeforeUpdate</title>
  <style>
      .news-container {
          width: 240px;
          height: 340px;
          border: 1px solid #000;
          overflow-y: scroll;
      }

      ul, li {
          text-decoration: none;
          list-style: none;
          margin: 0;
          padding: 0;
      }

      .news {
          width: 100%;
          height: 30px;
          line-height: 30px;
      }
  </style>
</head>
<body>
<div id="app"></div>
<script src="../lib/17/babel.min.js"></script>
<script src="../lib/17/react.development.js"></script>
<script src="../lib/17/react-dom.development.js"></script>
<script type="text/babel">
  class News extends React.Component {
    state = {
      newsArr: []
    }

    NewsRef = React.createRef()

    componentDidMount() {
      let count = 0
      this.timer = setInterval(() => {
        const {newsArr} = this.state
        this.setState({
          newsArr: ['news' + (++count), ...newsArr]
        })
      }, 1500)
    }

    componentWillUnmount() {
      clearInterval(this.timer)
    }

    // 用户在阅读新闻的时候，不要滚动
    getSnapshotBeforeUpdate() {
      return this.NewsRef.current.scrollHeight
    }

    componentDidUpdate(props, state, snapshot) {
      this.NewsRef.current.scrollTop += (this.NewsRef.current.scrollHeight - snapshot)
    }

    render() {
      return (
        <div className="news-container" ref={this.NewsRef}>
          <ul>{this.state.newsArr.map((item, index) => {
            return <li className="news" key={index}>{item}</li>
          })}</ul>
        </div>
      )
    }
  }

  ReactDOM.render(<News/>, document.querySelector('#app'))
</script>
</body>
</html>
